<template>
  <!-- device != 'mobile' -->
  <div class="box" :style="{ height: screenHeight + 'px' }">
    <div class="left" v-if="showImgList" :style="{ height: screenHeight + 'px' }">
      <div class="left_top">
        <el-select v-model="queryfaceLight" placeholder="光照类型" @change="getImgList" style="width:118px;height:28px"
          clearable class="left_top_photoMark">
          <el-option v-for="dict in queryfaceLightArr" :key="dict.value" :label="dict.label"
            :value="dict.value"></el-option>
        </el-select>
      </div>
      <div class="image_list">
        <!-- lazy -->
        <el-image class="img-style" v-for="(item, index) in showImgListArr" :key="index" fit="contain"
          :src="item.thumbnail" :class="{ selected: index == selectedIndex }" @click="changeImage(index)"></el-image>
      </div>
    </div>
    <!-- <div class="leftBottom" v-if="device == 'mobile' && showImgList">
      <div class="image_list">
        <el-image
          class="img-style"
          v-for="(item, index) in imgList"
          :key="index"
          :src="item.thumbnail"
          fit="contain"
          :class="{ selected: index == selectedIndex }"
          lazy
          @click="changeImage(index)"
        ></el-image>
      </div>
    </div> -->
    <div class="middle" :style="{ height: screenHeight + 'px' }">
      <drawboard :url="selectdUrl" @updateData="updateData" :labelDataOrigin="selectdPoints" @clearAllCb="clearAllCb"
        :currentEventName="currentEventName" @annotation-drawing-end="annotationDrawingEnd"
        :notSharePageEnter="notSharePageEnter" style="width: 100%; height: 100%" ref="myDrawBoard"
        @emitRenderDateEleMarkOptions="emitRenderDateEleMarkOptions">
        <template slot="bottomBar" style="text-align: center; display: flex; flex-wrap: wrap">
          <el-button type="primary" class="bottomBar_btn" size="mini" @click="prevImage()"><i
              class="el-icon-d-arrow-left"></i>上一张</el-button>
          <el-button type="primary" class="bottomBar_btn" size="mini" @click="nextImage()">下一张 <i
              class="el-icon-d-arrow-right"></i></el-button>
          <el-button v-if="isAdmin || isUpdate == 1" type="primary" class="bottomBar_btn" size="mini"
            @click="downLoadphoto()"><i class="el-icon-download"></i>下载</el-button>
          <el-button v-if="libraryId" type="primary" class="bottomBar_btn" icon="el-icon-delete" size="mini"
            @click="delImage()">剔除
          </el-button>
          <el-button type="primary" class="bottomBar_btn" size="mini"
            :class="[rightBoxStatus == 2 ? 'activeClass' : 'defaultClass']"
            @click="changerightBoxStatus(2)">照片信息</el-button>
          <el-button type="primary" class="bottomBar_btn" size="mini"
            :class="[rightBoxStatus == 1 ? 'activeClass' : 'defaultClass']"
            @click="changerightBoxStatus(1)">标注信息</el-button>
          <el-button type="primary" class="bottomBar_btn" size="mini"
            :class="[rightBoxStatus == 3 ? 'activeClass' : 'defaultClass']"
            @click="changerightBoxStatus(3)">隐藏信息</el-button>

          <el-button type="suceess" class="bottomBar_btn" size="mini" @click="closeshowImgList">{{ showImgList ?
    "收起照片列表" : "展开照片列表" }}</el-button>
          <el-button type="suceess" class="bottomBar_btn" size="mini" @click="closedEvent"
            style="color:red">退出关闭</el-button>
          <el-button v-if="currentImgInfo.photoType == 1 && currentImgInfo.photoIndex" type="success"
            class="bottomBar_btn" size="mini" @click="openAIReport(currentImgInfo.photoIndex)">AI分析报告</el-button>
        </template>
      </drawboard>
    </div>
    <div class="rightBox" :style="{ height: screenHeight + 'px' }" v-if="rightBoxStatus == 1 || rightBoxStatus == 2"
      @click="rightBoxStatus = 3">
      <div class="right" v-if="rightBoxStatus == 1" @click.stop="" :style="{ height: screenHeight + 'px' }">
        <renderDataEle :libraryId="libraryId" :labelData="labelData" @markShowEvent="markShowEvent"
          @selectedFigure="selectedFigure" @deleteFigure="deleteFigure" @filterMark="filterMark" ref="renderDataEle">
        </renderDataEle>
      </div>
      <div class="baseInfo" v-if="rightBoxStatus == 2" :style="{ height: screenHeight + 'px' }">
        <div class="baseInfo-title">照片信息</div>
        <div class="baseInfo-text">姓名:{{ currentImgInfo.patientName }}</div>
        <div class="baseInfo-text">年龄:{{ currentImgInfo.age }}</div>
        <div class="baseInfo-text">
          医生诊断:{{ currentImgInfo.doctorDiagnosis }}
        </div>
        <div class="baseInfo-text">
          采集状态:{{
    this.matchDict("sys_diagnosis_status", currentImgInfo.status)
  }}
        </div>
        <div class="baseInfo-text">
          采集设备:{{
      this.matchDict("photo_upload_type", currentImgInfo.type)
    }}
        </div>
        <div class="baseInfo-text">
          采集日期:{{ currentImgInfo.createTime }}
        </div>
        <div class="baseInfo-text">采集人:{{ currentImgInfo.nickName }}</div>
        <div class="baseInfo-text" v-if="currentImgInfo.scoreAi" style="color:red;font-weight:700">
          {{
    currentImgInfo.scoreAi
      ? "Ai mMASI评分:" + currentImgInfo.scoreAi.toFixed(1) + "分"
      : ""
  }}
        </div>
        <div class="baseInfo-text" v-if="scoreAiAll" style="color:red;font-weight:700">
          Ai mMASI总分:{{ scoreAiAll.toFixed(1) }}分
        </div>
        <div class="baseInfo-text">
          光照类型:{{
    this.matchDict("photo_lighting_type", currentImgInfo.faceLight)
  }}
        </div>
        <div class="baseInfo-text">
          部位:{{ this.matchDict("sys_face_part", currentImgInfo.facePart) }}
        </div>
        <div class="baseInfo-text">
          文件大小:{{ (currentImgInfo.fileSize / 1024 / 1024).toFixed(2) }}M
        </div>
        <div class="baseInfo-text">
          压缩比:{{ currentImgInfo.compressionRatio }}
        </div>
      </div>
    </div>
    <!-- 报告预览 start -->
    <el-dialog title="报告预览" :visible.sync="reportVisiable" :modal="true" :append-to-body="true" width="1060px">
      <div style="height:80vh">
        <iframe :src="reportURL" style="width:100%;min-height: 100%;"></iframe>
      </div>

    </el-dialog>
  </div>
</template>

<script>
import {
  updatePhotoMarkStatus,
  deleteLibraryPhotos,
  getDicts,
} from "@/api/system/annotationLibrary";
import renderDataEle from "./renderDataEle.vue";
import {
  addPicMark,
  delPicMark,
  picDetailByPhotoId,
} from "@/api/photoMark/index";
import {
  prevLibraryPhoto,
  nextLibraryPhoto,
} from "@/api/system/annotationLibrary";
import { mapGetters } from "vuex";
export default {
  name: "photoMark",
  components: { renderDataEle },
  props: [
    "currentUrl",
    "imgList",
    "myImgIndex",
    "notSharePageEnter",
    "libraryId",
    'libraryquery',
  ],
  dicts: [
    "sys_diagnosis_status",
    "photo_upload_type",
    "photo_lighting_type",
    "sys_face_part",
  ],
  data() {
    return {
      showImgListArr: [],
      queryfaceLight: '',
      reportVisiable: false,
      reportURL: '',
      // baseUrl: 'http://www.aikeji.top:10000/prod-api/',
      baseUrl: process.env.VUE_APP_BASE_API,
      selectdUrl: "",
      selectedIndex: 0,
      labelData: [],
      selectdPoints: [],
      currentImgInfo: {},
      currentEventName: "AI",
      scoreAiAll: "",
      filterSMarkId: null,
      rightBoxStatus: this.libraryId ? 1 : 2,
      showImgList: true,
      screenHeight: 0,
      imgShowContainerH: 0,//显示图片高度
      queryfaceLightArr: [],//筛选区域
      queryfaceLightId: [],//筛选id集合
    };
  },

  created() {



    // this.selectdUrl = this.imgList[0]
    // http://www.aikeji.top:10000/prod-api/profile/uploa…12086)%2020230317160507036_20230508110118A011.png
  },
  beforeMount() {
    window.addEventListener('resize', this.$_resizeHandler)
  },
  mounted() {
    console.log("this.libraryId*******************************")
    console.log(this.libraryId)
    window.screenHeight = document.body.clientHeight;
    this.screenHeight = window.screenHeight;

    this.imgShowContainerH = this.screenHeight - 40
    // this.selectdUrl = this.currentUrl
    this.getFaceList('photo_lighting_type')
    this.getImgList()
  },
  computed: {
    ...mapGetters(["token", "avatar", "isUpdate", "device", "nickName"]),
    isAdmin() {
      return this.$store.state.user.name === "admin" ? true : false;
    },
  },
  watch: {},
  methods: {
    getFaceList(type) {
      let that = this
      this.scoreAiAll = 0;

      console.log(this.imgList)
      getDicts(type).then((res) => {
        if (res.code === 200) {
          let data = res.data
          let photoLightTypeArr = data
          this.imgList.forEach((item) => {
            console.log(item.scoreAi)
            if (item.scoreAi) {
              that.scoreAiAll += item.scoreAi;
            }
            if (!this.queryfaceLightId.includes(item.faceLight)) {
              that.queryfaceLightId.push(item.faceLight)
              let objItem = photoLightTypeArr.find(obj => obj.dictValue === item.faceLight);
              let newObj = {
                value: objItem.dictValue,
                label: objItem.dictLabel
              }
              that.queryfaceLightArr.push(newObj)
            }
          });
        }
      })

    },
    getImgList() {

      // console.log(this.imgList)
      if (this.queryfaceLight) {
        let data = []
        this.imgList.forEach((item) => {
          if (this.queryfaceLight == item.faceLight) {
            data.push(item)
          }
        });
        this.showImgListArr = data
        this.selectdUrl = data[0].photoAddress;
        this.selectedIndex = 0;
        this.getCurrentAiPoints();
        this.currentImgInfo = this.showImgListArr[0];
      } else {
        this.showImgListArr = this.imgList
        this.selectdUrl = this.currentUrl;
        this.selectedIndex = this.myImgIndex;
        this.getCurrentAiPoints();
        this.currentImgInfo = this.showImgListArr[this.myImgIndex];
      }
    },
    openAIReport(p_index) {
      const { href } = this.$router.resolve({
        name: 'aiAnalysisReport',
        path: '/aiAnalysisReport',
        query: {
          id: p_index,
        }
      })
      console.log('href---', href)
      this.reportURL = href
      this.reportVisiable = true

    },
    $_resizeHandler() {
      window.screenHeight = document.body.clientHeight;
      this.screenHeight = window.screenHeight;

      this.imgShowContainerH = this.screenHeight - 40

    },
    downLoadphoto() {
      const imgUrl = this.currentImgInfo.photoAddress;// 图片链接
      // const a = document.createElement('a');
      // 这里是将url转成blob地址，
      let that = this
      fetch(imgUrl)  // 跨域时会报错
        .then(res => res.blob())
        .then(blob => { // 将链接地址字符内容转变成blob地址
          that.convertToJPG(URL.createObjectURL(blob), 1, function (dataURL) {
            // 这里的dataURL就是转换后的JPG图像的DataURL
            // 如果需要将此图像下载为文件，可以使用以下代码
            var link = document.createElement('a');
            link.href = dataURL;
            link.download =that.currentImgInfo.patientName+ that.currentImgInfo.visitNum + "(采集时间：" +that.currentImgInfo.createTime + ")"; //imgUrl.replace(/(.*\/)*([^.]+.*)/ig,"$2").split("?")[0] 下载文件的名字
            document.body.appendChild(link);
            link.click();
            window.URL.revokeObjectURL(link.href);
            document.body.removeChild(link);
          });
        })
    },
    convertToJPG(sourceImage, quality, callback) {
      var image = new Image();
      image.src = sourceImage;
      image.onload = function () {
        var canvas = document.createElement('canvas');
        console.log(canvas)
        canvas.width = image.width;
        canvas.height = image.height;
        var ctx = canvas.getContext('2d');
        ctx.drawImage(image, 0, 0);
        var dataURL = canvas.toDataURL('image/jpeg', quality);
        callback(dataURL);
      };
    },
    emitRenderDateEleMarkOptions() {
      this.$refs.renderDataEle.getList();
    },
    closeshowImgList() {
      this.showImgList = !this.showImgList;
    },
    closedEvent() {
      this.$emit("closedEvent");
    },
    changerightBoxStatus(data) {
      this.rightBoxStatus = data;
    },
    changeImage(index) {
      this.selectedIndex = index;
      this.selectdUrl = this.showImgListArr[index].photoAddress;
      this.markShowEvent(this.currentEventName);
      this.currentImgInfo = this.showImgListArr[index];
    },
    prevImage() {
      //如果是从标注库进的 上一张下一张要请求接口
      if (this.libraryId) {
        prevLibraryPhoto({
          researchLibrariesId: this.libraryId,
          type: this.libraryquery.type,
          visitNum: this.libraryquery.visitNum,
          facePart: this.libraryquery.facePart,
          faceLight: this.libraryquery.faceLight,
          status: this.libraryquery.status,
          sMark: this.libraryquery.sMark,
          photoId: this.showImgListArr[0].photoId,
        }).then((res) => {
          if (res.code === 200) {
            if (res.data != null) {
              this.showImgListArr = [res.data];
              this.changeImage(0);
            } else {
              this.$message.warning("已经是第一张了");
            }
          }
        });
      } else {
        //不从标注库进还按照原来的逻辑走
        if (this.selectedIndex > 0) {
          this.changeImage(this.selectedIndex - 1);
        } else {
          this.$message.warning("已经是第一张了");
        }
      }
    },
    nextImage() {
      //如果是从标注库进的 上一张下一张要请求接口
      if (this.libraryId) {
        nextLibraryPhoto({
          researchLibrariesId: this.libraryId,
          type: this.libraryquery.type,
          visitNum: this.libraryquery.visitNum,
          facePart: this.libraryquery.facePart,
          faceLight: this.libraryquery.faceLight,
          status: this.libraryquery.status,
          sMark: this.libraryquery.sMark,
          photoId: this.showImgListArr[0].photoId,
        }).then((res) => {
          if (res.code === 200) {
            if (res.data != null) {
              this.showImgListArr = [res.data];
              this.changeImage(0);
            } else {
              this.$message.warning("已经是最后一张了");
            }
          }
        });
      } else {
        console.log(this.showImgListArr.length)
        console.log(this.selectedIndex)
        //不从标注库进还按照原来的逻辑走
        if (this.selectedIndex < this.showImgListArr.length - 1) {
          this.changeImage(this.selectedIndex + 1);
        } else {
          this.$message.warning("已经是最后一张了");
        }
      }
    },
    delImage() {
      this.$confirm("此操作将删除所选照片, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deleteLibraryPhotos(this.libraryId, this.currentImgInfo.photoId).then(
            (response) => {
              if (response.code == 200) {
                this.$modal.msgSuccess("删除成功");
              }
            }
          );
        })
        .catch((error) => {
          console.log(error);
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    updateData(data) {
      this.labelData = JSON.parse(JSON.stringify(data));
    },
    deleteFigure(index, figure) {
      if (figure.markId) {
        delPicMark(figure.markId).then((res) => {
          if (res.code === 200) {
            this.$message.success("删除成功");
            this.markShowEvent(this.currentEventName);
          }
        });
        if (this.labelData.length == 1 && this.libraryId) {
          this.updateCurrentPhotoMarkStatus();
        }
      }
      this.$refs.myDrawBoard.deleteFigure(index);
    },
    updateCurrentPhotoMarkStatus() {
      if (this.libraryId) {
        updatePhotoMarkStatus(this.libraryId, this.currentImgInfo.photoId).then(
          (res) => {
            if (res.code === 200) {
            }
          }
        );
      }

    },
    selectedFigure(index) {
      this.$refs.myDrawBoard.selectedFigure(index);
    },
    clearAllCb() {
      this.selectdPoints = [];
    },

    /** id转化成对应的文字 */
    matchDict: function (key, id) {
      let _this = this;
      const result = _this.dict.type[key];
      let textValue = "";
      result.forEach((item) => {
        if (item.raw.dictValue == id) {
          textValue = item.raw.dictLabel;
        }
      });
      return textValue;
    },
    annotationDrawingEnd(data) {
      this.addPhotoMark(data);
    },
    addPhotoMark(data) {
      let mdata = null;
      if (this.currentEventName == "scientific") {
        mdata = {
          researchLibrariesId: this.libraryId, //科研标注会多一个标注库Id
          patientId: this.currentImgInfo.patientId,
          visitNum: this.currentImgInfo.visitNum,
          photoId: this.currentImgInfo.photoId,
          points: JSON.stringify(data.points),
          type: data.type,
          sMarkId: data.sMarkId,
          options: data.options,
          kind:
            this.currentEventName == "artificial"
              ? "2"
              : this.currentEventName == "scientific"
                ? "3"
                : null,
        };
      } else {
        mdata = {
          patientId: this.currentImgInfo.patientId,
          visitNum: this.currentImgInfo.visitNum,
          photoId: this.currentImgInfo.photoId,
          points: JSON.stringify(data.points),
          type: data.type,
          sMarkId: data.sMarkId,
          options: data.options,
          kind:
            this.currentEventName == "artificial"
              ? "2"
              : this.currentEventName == "scientific"
                ? "3"
                : null,
        };
      }
      addPicMark(mdata).then((res) => {
        this.markShowEvent(this.currentEventName);
      });
    },
    markShowEvent(eventName) {
      this.currentEventName = eventName;
      switch (eventName) {
        case "origin":
          this.clearAllCb();
          this.changemarkType(eventName);
          break;
        case "AI":
          this.getCurrentAiPoints();
          this.changemarkType(eventName);
          break;
        case "artificial":
          this.getCurrentArtificialPoints();
          this.changemarkType(eventName);
          break;
        case "scientific":
          this.getCurrentScientificPoints();
          this.changemarkType(eventName);
          break;
      }
    },
    changemarkType(eventName) {
      this.$refs.myDrawBoard.renderDataEleEventName = eventName;
      this.$refs.myDrawBoard.changeMarkType();
    },
    filterMark(data) {
      this.filterSMarkId = data;
      if (this.libraryId) {
        this.getCurrentScientificPoints();
      } else {
        this.getCurrentArtificialPoints();
      }
    },
    getCurrentAiPoints() {
      let mdata = {
        photoId: this.showImgListArr[this.selectedIndex].photoId,
        kind: "1",
      };
      picDetailByPhotoId(mdata).then((res) => {
        this.selectdPoints = this.formatPoints(res.data.points);
      });
    },
    getCurrentArtificialPoints() {
      let mdata = {
        photoId: this.showImgListArr[this.selectedIndex].photoId,
        kind: "2",
        sMarkId: this.filterSMarkId,
      };
      picDetailByPhotoId(mdata).then((res) => {
        this.selectdPoints = this.formatSysPhotoMarks(res.data.sysPhotoMarks);
      });
    },
    getCurrentScientificPoints() {
      let mdata = {
        photoId: this.showImgListArr[this.selectedIndex].photoId,
        kind: "3",
        sMarkId: this.filterSMarkId,
      };
      picDetailByPhotoId(mdata).then((res) => {
        this.selectdPoints = this.formatSysPhotoMarks(res.data.sysPhotoMarks);
        this.$refs.renderDataEle.getList();
      });
    },
    getPicDetail(photoId) {
      picDetailByPhotoId(photoId).then((res) => { });
    },
    //格式化画图组件点位格式数据
    formatPoints(data) {
      if (data != null) {
        let mData = [];
        JSON.parse(data).forEach((item, index) => {
          let itPoint = [];
          item.forEach((it, mindex) => {
            itPoint.push({ x: it[0], y: it[1] });
            if (item.length - 1 === mindex) {
              //最后一个点连接到第一个点形成闭合
              itPoint.push({ x: item[0][0], y: item[0][1] });
            }
          });
          mData.push({ points: itPoint, type: "route" });
        });
        return mData;
      } else {
        return null;
      }
    },
    //格式化画图组件人工标注点位格式数据
    formatSysPhotoMarks(data) {
      return data.map((item) => {
        return { ...item, points: JSON.parse(item.points) };
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.box {
  // height: 750px;
  display: flex;
  flex-direction: row;
  height: calc(100vh - 98px);
  // height:90vh;
  width: 100%;
  color: #bfcbd9;
  position: relative;
}

::v-deep .left::-webkit-scrollbar {
  width: 2px;
}

::v-deep .left::-webkit-scrollbar-thumb {
  border-radius: 2px;
  background-color: #1890FF;
  cursor: pointer;
  z-index: 999;
}

.left {
  padding-top: 40px;
  background-color: #282828;
  flex: 0px 0 128px;
  // border-right: 1px solid #171717;
  width: 128px; //41px;
  overflow-y: auto;
  overflow-x: hidden;
  position: relative;

  &_top {
    position: fixed;
    z-index: 8;
    top: 0px;
    left: 0px;
    width: 128px;
    height: 40px;
    background: #282828;

    &_photoMark {
      margin-top: 4px;
      margin-left: 4px;

      ::v-deep .el-input--medium .el-input__inner {
        height: 28px;
        line-height: 28px;
      }

      ::v-deep .el-input--medium .el-input__icon {
        line-height: 28px;
      }
    }
  }

  .image_list {
    padding: 4px;
    width: 108px;
    margin: 0 auto;

    .img-style {
      display: block;
      width: 100px;
      height: 131px;
      border-radius: 4px;
      cursor: pointer;
      margin-bottom: 6px;
      object-fit: cover;
    }
  }
}

.middle {
  flex: 1 1 auto;
  display: flex;
  flex-direction: column;
}

.rightBox {
  position: absolute;
  top: 0px;
  right: 0px;
  height: 100%;
  width: 200px;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
}

.right {
  background-color: #282828;
  flex: 0 0 200px;
  border-left: 1px solid #171717;
  width: 200px;
  overflow: hidden;
}

::v-deep .right::-webkit-scrollbar {
  display: none !important;
}

.baseInfo {
  // background-color: #282828;
  // flex: 0 0 200px;
  border-left: 1px solid #171717;
  width: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  padding-left: 8px;
}

.baseInfo-title {
  color: #fff;
  height: 41px;
  text-align: center;
  line-height: 41px;
}

.baseInfo-text {
  color: #fff;
  margin-top: 12px;
  // text-align: center;
  line-height: 20px;
  word-wrap: break-word;
}

.selected {
  border: 2px solid yellow;
}

.leftBottom {
  position: fixed;
  bottom: 0px;
  left: 0px;
  width: 100%;

  height: 100px;
  z-index: 999;
  background: rgba(0, 0, 0, 0.5);

  .img-style {
    width: 50px;
    height: 75px;
    margin: 10px;
    display: inline-block;
  }

  .image_list {
    overflow: hidden;
    overflow-x: auto;
    white-space: nowrap;
  }
}

//整个滚动条
.image_list::-webkit-scrollbar {
  width: 6px;
  height: 6px;
  display: none;
  background-color: #282828;
}

//滚动条轨道
.image_list::-webkit-scrollbar-track {
  background-color: #d3dce6;
}

//滚动条上的滚动滑块
.image_list::-webkit-scrollbar-thumb {
  background-color: #99a9bf;
  border-radius: 20px;
}

@media only screen and (max-width: 992px) {
  // .left::v-deep {
  //   width: 80px;
  //   flex: 0 0 80px;
  // }

  // .rightBox {
  //   width: 200px;
  //   font-size: 14px;
  // }
}

@media only screen and (max-width: 550px) {
  // .left::v-deep {
  //   width: 30px;
  //   flex: 0 0 30px;
  // }

  // .baseInfo {
  //   width: 200px;
  //   font-size: 14px;
  // }
}
</style>
